//
//  ImageExt.swift
//  covermedia
//
//  Created by listen on 16/5/8.
//  Copyright © 2016年 covermedia. All rights reserved.
//

import Foundation
import ImageIO
import UIKit

public extension UIImage  {
 
    public class func imageWithSize(_ size:CGSize, drawBlock:(_ context:CGContext)->Void) -> UIImage? {

        UIGraphicsBeginImageContextWithOptions(size, false, 0)
        let context = UIGraphicsGetCurrentContext()
        if (context == nil) {
            return nil
        }
        drawBlock(context!)
        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return image

    }
}

public extension UIImage {
    
    public class func animatedImageWithSource(_ source: CGImageSource) -> [UIImage] {
        let count = CGImageSourceGetCount(source)
        var images = [CGImage]()
        
        // Fill arrays
        for i in 0..<count {
            // Add image
            if let image = CGImageSourceCreateImageAtIndex(source, i, nil) {
                images.append(image)
            }
        }
        
        return images.flatMap { (image:CGImage) -> UIImage? in
            return UIImage.init(cgImage: image)
        }
    }
    
    public class func gifWithName(_ name: String) -> [UIImage] {
        guard let bundleURL = Bundle.main.url(forResource: name, withExtension: "gif") else {
                return []
        }
        
        // Validate data
        guard let imageData = try? Data.init(contentsOf: bundleURL) else {
            return []
        }
        
        guard let source = CGImageSourceCreateWithData(imageData as CFData, nil) else {
            return []
        }
        
        return UIImage.animatedImageWithSource(source)
    }
}

// MARK: - 制作圆角头像
public extension UIImage {
    //制作圆角头像
    public func roundImage(_ success: @escaping (_ roundImage: UIImage) -> ()) {
        DispatchQueue.global().async {
            let size = self.size
            UIGraphicsBeginImageContextWithOptions(size, false, 0)
            let ctx = UIGraphicsGetCurrentContext()
            let path = UIBezierPath()
            path.addArc(withCenter: CGPoint.init(x: size.width * 0.5, y:size.height * 0.5), radius: size.height * 0.5, startAngle: 0, endAngle: CGFloat(M_PI) * 2, clockwise: false)
            ctx!.addPath(path.cgPath)
            ctx!.clip()
            self.draw(at: CGPoint.zero)
            let clipImage = UIGraphicsGetImageFromCurrentImageContext()
            UIGraphicsEndImageContext()
            DispatchQueue.main.async {
                success(clipImage!)
            }
        }
    }
}


// MARK: - 图片UIImage相关扩展
public extension CMExt where DT == UIImage {
    
    /// 压缩图片
    ///
    /// - Parameter shortSide: 短的边长（长宽的较小值）最大值
    /// - Returns: 压缩后的图片
    public func resize(limit shortSide:CGFloat = 1024) -> UIImage {
        var targetSize = v.size
        if min(targetSize.width, targetSize.height) > shortSide {
            if targetSize.width > targetSize.height {
                targetSize = CGSize.init(width: shortSide * targetSize.width / targetSize.height , height: shortSide)
            } else {
                targetSize = CGSize.init(width: shortSide , height: shortSide * targetSize.height / targetSize.width)
            }
            UIGraphicsBeginImageContext(targetSize)
            v.draw(in: CGRect.init(origin: CGPoint.zero, size: targetSize))
            let newImage = UIGraphicsGetImageFromCurrentImageContext()
            UIGraphicsEndImageContext()
            return newImage ?? v
        }
        return v
    }
}
